import { login } from '@/api/login'
import { updateInfo } from '@/api/home'
import { getToken, setToken, removeToken } from '@/utils/auth'

const LACAL_USER = 'THREE_USERINFO';

const user = {
  state: {
    token: getToken(),
    userInfo:JSON.parse(localStorage.getItem(LACAL_USER)) || '' //初始值去缓存中取
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    UPDATE_INFO : (state, userInfo) => {
      state.userInfo = Object.assign({},state.userInfo,userInfo)
    }
  },

  actions: {
    // 登录1
    Login({ commit }, userInfo) {
      const phone = userInfo.phone.trim()
      return new Promise((resolve, reject) => {
        login(phone, userInfo.password).then(response => {
          let data = response.data
          localStorage.setItem(LACAL_USER,JSON.stringify(data)) //把个人信息放在缓存中
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          commit('SET_INFO', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    UpdateInfo({ commit }, userInfo){
      return new Promise((resolve , reject)=>{
        updateInfo(userInfo).then(res=>{
          if(userInfo.flag){
            delete userInfo.flag
          }
          localStorage.setItem(LACAL_USER,JSON.stringify(userInfo))
          commit('UPDATE_INFO',userInfo)
          resolve()
        }).catch(res=>{
          reject(res)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        localStorage.removeItem(LACAL_USER)
        removeToken()
        resolve()
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    // FedLogOut({ commit }) {
    //   return new Promise(resolve => {
    //     commit('SET_TOKEN', '')
    //     removeToken()
    //     resolve()
    //   })
    // }
  }
}

export default user
